from BasicLibraries import *
import regressions as regression_list

reg = regression_list.RegressionList()
controls_ = ['firm_size', 'Tangibility', 'MTB',  'turnover', 'IMR' ]
INTERACTIONTYPE = 'COMPETITOR'

class MAIN():
    def __init__(self):
        pass
    def make_total_effect(self, emission_type, tc, golden_data, panel_data, controls_, dummies, scaler_type='relative'):
        TotalDist, efx, efxL, efxU = reg.get_total_effect(emission_type,
                                  tc, golden_data, panel_data, 
                                  controls_, dummies,
                                  scaler_type=scaler_type,
                                  mediating_controls = [],
                                  initiative_set='ALL',
                                  strategy_type = None,
                                  INTERACTIONTYPE='COMPETITOR', 
                                  number_of_lags = 2)
        return TotalDist, efx, efxL, efxU
    def get_table(self, emission_type, tc, golden_data, panel_data, strategy_list, controls_, dummies, scaler_type='relative',make_total=False):
        NUM_EM_LAG = 2
        initiatives_subset = 'ALL'
        vector_for_table = []
        recall_distributions = pd.DataFrame()
        SampleDescr = pd.DataFrame()
        for strategy_ in strategy_list:
            if strategy_ == 'Size':
                mediating_controls = []
                controls_  = ['at_usd', 'Tangibility', 'Profitability']
            else:
                mediating_controls = ['investment', 'Profitability']
                controls_ = ['firm_size', 'Tangibility', 'MTB',  'turnover', 'firm_size_t1']
            
            if strategy_ == 'Initiatives intensity': strategy_ = None
            print('Running strategy:', strategy_)
            x, mediation_analysis, TotalEffectDist, efx, efxL, efxU, \
             mediation_mean, lower_b, upper_b, exp_on_med, med_on_out, boot_samples, proportion, beta_tilde, total_effect, prop_med, bootstrappedSAMPLEVARS\
                                                    = reg.effect_on_emissions(emission_type,
                                                                              tc, golden_data, panel_data, 
                                                                              controls_, dummies,
                                                                              scaler_type=scaler_type,
                                                                              mediating_controls = mediating_controls,
                                                                              initiative_set=initiatives_subset,
                                                                              strategy_type = strategy_,
                                                                              INTERACTIONTYPE='COMPETITOR', 
                                                                              number_of_lags = NUM_EM_LAG,
                                                                              make_total_effect=make_total)
            exp_on_med_ = pd.DataFrame(exp_on_med)
            exp_l, exp_u = reg.get_bounds(exp_on_med_.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            med_on_out_ = pd.DataFrame(med_on_out)
            med_l, med_u = reg.get_bounds(med_on_out_.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            betTLD = pd.DataFrame(beta_tilde)
            bet_l, bet_u = reg.get_bounds(betTLD.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            totEFX = pd.DataFrame(total_effect)
            tot_l, tot_u = reg.get_bounds(totEFX.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            prop_med = pd.DataFrame(prop_med)
            if strategy_ == None and make_total == True:
                TotalEffectDistOUT = pd.DataFrame(TotalEffectDist)
            else:
                TotalEffectDistOUT = 0
            full_distributions = pd.concat((exp_on_med_, med_on_out_, betTLD, prop_med), axis = 1)
            full_distributions.columns = ['phi', 'eta', 'betaT', 'PropMediation']
            full_distributions['StrategyType'] = [strategy_]*len(full_distributions)
            recall_distributions = pd.concat((recall_distributions, full_distributions))
            
            bootstrappedSAMPLEVARS['StrategyType'] = [strategy_]*len(bootstrappedSAMPLEVARS)
            SampleDescr  = pd.concat((SampleDescr, bootstrappedSAMPLEVARS))
            
            

            if efx != -1:
                total_estimated_effect = str(np.round(efx, 3))+' ['+str(np.round(efxL, 3))+','+str(np.round(efxU, 3))+']'
            else:
                total_estimated_effect = ''
            betT = str(np.round(betTLD.mean().iloc[0], 3))+' ['+str(np.round(bet_l, 3))+','+str(np.round(bet_u, 3))+']'
            phi = str(np.round(exp_on_med_.mean().iloc[0], 3))+' ['+str(np.round(exp_l, 3))+','+str(np.round(exp_u, 3))+']'
            eta = str(np.round( med_on_out_.mean().iloc[0], 3))+' ['+str(np.round(med_l, 3))+','+str(np.round(med_u, 3))+']'
            totE = str(np.round(totEFX.mean().iloc[0], 3))+' ['+str(np.round(tot_l, 3))+','+str(np.round(tot_u, 3))+']'
            prod_coeff = str(np.round(mediation_mean,3))+' ['+str(np.round(lower_b, 3))+','+str(np.round(upper_b, 3))+']'
        
            vector_for_table.append([total_estimated_effect,
                                     totE,
                                     betT,
                                     phi,
                                     eta,
                                     prod_coeff,
                                     proportion])
            s = pd.DataFrame(vector_for_table)
            s.columns = [r'$\beta$', r'$\tilde{\beta} + \phi\eta$', r'$\tilde{\beta}$', r'$\phi$', r'$\eta$', r'$\phi\eta$', r'$\frac{\phi\eta}{\phi\eta+\tilde{\beta}}$']
            print(s)
        vector_for_table = pd.DataFrame(vector_for_table)
        vector_for_table.index = strategy_list
        vector_for_table.columns = [r'$\beta$', r'$\tilde{\beta} + \phi\eta$', r'$\tilde{\beta}$', r'$\phi$', r'$\eta$', r'$\phi\eta$', r'$\frac{\phi\eta}{\phi\eta+\tilde{\beta}}$']
        return vector_for_table, TotalEffectDistOUT, recall_distributions, SampleDescr

    

    
    def robs_tables(self, emission_type, tc, golden_data, panel_data, strategy_list, controls_, dummies, med_controls, scaler_type='relative',make_total=False):
        NUM_EM_LAG = 2
        initiatives_subset = 'ALL'
        vector_for_table = []
        recall_distributions = pd.DataFrame()
        SampleDescr = pd.DataFrame()
        for strategy_ in strategy_list:
            if strategy_ == 'Initiatives intensity': strategy_ = None
            print('Running strategy:', strategy_)
            x, mediation_analysis, TotalEffectDist, efx, efxL, efxU, \
             mediation_mean, lower_b, upper_b, exp_on_med, med_on_out, boot_samples, proportion, beta_tilde, total_effect, prop_med, bootstrappedSAMPLEVARS\
                                                    = reg.effect_on_emissions(emission_type,
                                                                              tc, golden_data, panel_data, 
                                                                              controls_, dummies,
                                                                              scaler_type=scaler_type,
                                                                              mediating_controls = med_controls,
                                                                              initiative_set=initiatives_subset,
                                                                              strategy_type = strategy_,
                                                                              INTERACTIONTYPE='COMPETITOR', 
                                                                              number_of_lags = NUM_EM_LAG,
                                                                              make_total_effect=make_total)
            exp_on_med_ = pd.DataFrame(exp_on_med)
            exp_l, exp_u = reg.get_bounds(exp_on_med_.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            med_on_out_ = pd.DataFrame(med_on_out)
            med_l, med_u = reg.get_bounds(med_on_out_.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            betTLD = pd.DataFrame(beta_tilde)
            bet_l, bet_u = reg.get_bounds(betTLD.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            totEFX = pd.DataFrame(total_effect)
            tot_l, tot_u = reg.get_bounds(totEFX.sort_values(by = 0).reset_index()[0], boot_samples, 0.05)
            prop_med = pd.DataFrame(prop_med)
            
            
            if strategy_ == None and make_total == True:
                TotalEffectDistOUT = pd.DataFrame(TotalEffectDist)
            else:
                TotalEffectDistOUT = 0

            
            bootstrappedSAMPLEVARS['StrategyType'] = [strategy_]*len(bootstrappedSAMPLEVARS)
            SampleDescr  = pd.concat((SampleDescr, bootstrappedSAMPLEVARS))
            
            
            full_distributions = pd.concat((exp_on_med_, med_on_out_, betTLD, prop_med), axis = 1)
            full_distributions.columns = ['phi', 'eta', 'betaT', 'PropMediation']
            full_distributions['StrategyType'] = [strategy_]*len(full_distributions)
            recall_distributions = pd.concat((recall_distributions, full_distributions))

            if efx != -1:
                total_estimated_effect = str(np.round(efx, 3))+' ['+str(np.round(efxL, 3))+','+str(np.round(efxU, 3))+']'
            else:
                total_estimated_effect = ''
            betT = str(np.round(betTLD.mean().iloc[0], 3))+' ['+str(np.round(bet_l, 3))+','+str(np.round(bet_u, 3))+']'
            phi = str(np.round(exp_on_med_.mean().iloc[0], 3))+' ['+str(np.round(exp_l, 3))+','+str(np.round(exp_u, 3))+']'
            eta = str(np.round( med_on_out_.mean().iloc[0], 3))+' ['+str(np.round(med_l, 3))+','+str(np.round(med_u, 3))+']'
            totE = str(np.round(totEFX.mean().iloc[0], 3))+' ['+str(np.round(tot_l, 3))+','+str(np.round(tot_u, 3))+']'
            prod_coeff = str(np.round(mediation_mean,3))+' ['+str(np.round(lower_b, 3))+','+str(np.round(upper_b, 3))+']'
        
            vector_for_table.append([total_estimated_effect,
                                     totE,
                                     betT,
                                     phi,
                                     eta,
                                     prod_coeff,
                                     proportion])
            s = pd.DataFrame(vector_for_table)
            s.columns = [r'$\beta$', r'$\tilde{\beta} + \phi\eta$', r'$\tilde{\beta}$', r'$\phi$', r'$\eta$', r'$\phi\eta$', r'$\frac{\phi\eta}{\phi\eta+\tilde{\beta}}$']
            print(s)
        vector_for_table = pd.DataFrame(vector_for_table)
        vector_for_table.index = strategy_list
        vector_for_table.columns = [r'$\beta$', r'$\tilde{\beta} + \phi\eta$', r'$\tilde{\beta}$', r'$\phi$', r'$\eta$', r'$\phi\eta$', r'$\frac{\phi\eta}{\phi\eta+\tilde{\beta}}$']
        return vector_for_table, TotalEffectDistOUT, recall_distributions, SampleDescr


    
    
    
    